﻿package 
{
    import flash.display.Sprite;
    import flash.events.EventDispatcher;
    import flash.events.KeyboardEvent;
    import flash.geom.Point;
    import flash.ui.Keyboard;

    public class Player extends EventDispatcher
    {
        private var m_player:Sprite = new Sprite();

        public function Player()
        {
            createPlayer();

            m_player;
        }

        public function getPlayer():Sprite
        {
            return m_player;
        }

        private function createPlayer():void
        {
            m_player.graphics.beginFill(0x000000);
            m_player.graphics.drawCircle(0, 0, GameConstants.PLAYER_RADIUS);
            m_player.graphics.endFill();

            m_player.x = GameConstants.START_X;
            m_player.y = GameConstants.START_Y;
        }

        public function onKeyDown(e:KeyboardEvent):void
        {
            switch (e.keyCode)
            {
            case Keyboard.UP :
                m_player.y -= (m_player.y - GameConstants.SPEED < GameConstants.WALL_THICKNESS) ? 0 : GameConstants.SPEED;
                break;
            case Keyboard.DOWN :
                m_player.y += (m_player.y + GameConstants.SPEED > GameConstants.HEIGHT - GameConstants.WALL_THICKNESS) ? 0 : GameConstants.SPEED;
                break;
            case Keyboard.LEFT :
                m_player.x -= (m_player.x - GameConstants.SPEED < GameConstants.WALL_THICKNESS) ? 0 : GameConstants.SPEED;
                break;
            case Keyboard.RIGHT :
                m_player.x += (m_player.x + GameConstants.SPEED > GameConstants.WIDTH - GameConstants.WALL_THICKNESS) ? 0 : GameConstants.SPEED;
                break;
            }

            dispatch();
        }

        private function dispatch():void
        {
            var playerEvent:PlayerEvent = new PlayerEvent(PlayerEvent.PLAYER_MOVES);
            playerEvent.playerX = m_player.x;
            playerEvent.playerY = m_player.y;

            dispatchEvent(playerEvent);
        }

        public function setPosition(newPos:Point):void
        {
            m_player.x = newPos.x;
            m_player.y = newPos.y;
        }
    }
}
